package club.emergency.wechat.common.https;

import club.emergency.wechat.common.utils.JsonConvert;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Create with IntelliJ IDEA
 * Project Name: business
 * Package Name: club.emergency.wechat_api.common.https
 * Date: 2018/12/12
 *
 * @author: 快乐的小菌菌
 * Description:
 */
public class HttpsPostRequestUtil {

    public String doJsonRequest(String url, Object requestBodyObj) {
        HttpPost post;
        String result = null;
        try {
            HttpClient httpClient = HttpClientBuilder.create().build();

            post = new HttpPost(url);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");

            // 构建消息实体
            String string = new JsonConvert<>().underscoresToCamelEncode(requestBodyObj);
            StringEntity entity = new StringEntity(string, StandardCharsets.UTF_8);
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String doMultipartRequest(String url, String fileName, byte[] bytes) {
        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = HttpClientBuilder.create().build();
        httpPost.addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8);
        builder.setMode(HttpMultipartMode.RFC6532);
        builder.addBinaryBody("media", bytes, ContentType.MULTIPART_FORM_DATA, fileName);
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        String result = null;
        try {
            HttpResponse response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}